﻿using Microsoft.International.Converters.PinYinConverter;
using System;
using System.Linq;
using System.Text;

namespace Util
{
    public class PinYinConverter
    {
        /// <summary>
        /// 获取文字频音
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetPinYin(string name)
        {
            StringBuilder stringBuilder = new StringBuilder();
            var array = name.ToArray();
            foreach (char item in array)
                stringBuilder.Append(
                    GetFirstChar(item));
            return stringBuilder.ToString();
        }

        /// <summary>
        /// 获取拼音首字母
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static char GetFirstChar(char c)
        {
            if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'))
            {
                return c;
            }
            else
            {
                try
                {
                    ChineseChar cc = new ChineseChar(c);
                    if (cc.Pinyins.Count > 0 && cc.Pinyins[0].Length > 0)
                    {
                        return cc.Pinyins[0][0];
                    }
                }
                catch (Exception ex)
                {
                    return c;
                }
                return c;
            }
        }
    }
}
